<template>
  <el-dialog
    v-model="visible"
    width="700px"
    :before-close="handleClose"
    class="unified-dialog monitor-edit-dialog"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon header-icon-primary">
          <el-icon><Edit /></el-icon>
        </div>
        <div class="header-content">
          <h3>编辑监控配置</h3>
          <p>修改Kafka Topic监控和告警参数</p>
        </div>
      </div>
    </template>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="140px"
      label-position="left"
      class="monitor-edit-form"
    >
      <!-- 基础信息 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Document /></el-icon>
          <span>基础信息</span>
        </div>
        
        <el-form-item label="Topic名称">
          <el-input v-model="form.topic_name" disabled />
          <span class="form-tip">Topic名称不可修改</span>
        </el-form-item>
        
        <el-form-item label="分区ID">
          <el-input-number v-model="form.partition_id" disabled style="width: 100%;" />
          <span class="form-tip">分区ID不可修改</span>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-input v-model="statusText" disabled />
          <span class="form-tip">状态由监控开关和告警开关自动计算，不可手动修改</span>
        </el-form-item>
      </div>
      
      <!-- 监控设置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><View /></el-icon>
          <span>监控设置</span>
        </div>
        
        <el-form-item label="启用监控" prop="is_monitored">
          <div class="switch-container">
            <el-switch
              v-model="form.is_monitored"
              :active-value="1"
              :inactive-value="0"
              size="large"
            />
            <div class="switch-description">
              <p class="description-title">监控数据收集</p>
              <p class="description-text">启用后将定时收集Topic的消息数据和Offset信息</p>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="启用告警" prop="is_alert_enabled">
          <div class="switch-container">
            <el-switch
              v-model="form.is_alert_enabled"
              :active-value="1"
              :inactive-value="0"
              size="large"
            />
            <div class="switch-description">
              <p class="description-title">消息延迟告警</p>
              <p class="description-text">启用后当消息延迟超过阈值时会发送告警通知</p>
            </div>
          </div>
        </el-form-item>
      </div>
      
      <!-- 告警配置 -->
      <div class="form-section">
        <div class="section-title">
          <el-icon><Bell /></el-icon>
          <span>告警配置</span>
        </div>
        
        <el-form-item label="告警阈值(小时)" prop="alert_threshold_hours">
          <el-input-number
            v-model="form.alert_threshold_hours"
            :min="1"
            :max="168"
            controls-position="right"
            class="number-input"
          />
          <span class="form-tip">消息延迟超过此阈值时触发告警，建议设置为24小时</span>
        </el-form-item>
        
        <el-form-item label="Webhook地址" prop="webhook_url">
          <el-input
            v-model="form.webhook_url"
            placeholder="企业微信/钉钉Webhook地址"
            clearable
          />
          <span class="form-tip">留空则使用系统默认配置</span>
        </el-form-item>
        
        <el-form-item label="首次告警时间" prop="alert_first_send_time">
          <el-time-picker
            v-model="formAlertTime"
            format="HH:mm"
            placeholder="选择时间"
            style="width: 100%;"
          />
          <span class="form-tip">每天首次告警的发送时间，建议设置为上班时间</span>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="第2次间隔(秒)" prop="alert_second_interval">
              <el-input-number
                v-model="form.alert_second_interval"
                :min="60"
                :max="86400"
                :step="60"
                controls-position="right"
                class="number-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第3次间隔(秒)" prop="alert_third_interval">
              <el-input-number
                v-model="form.alert_third_interval"
                :min="60"
                :max="86400"
                :step="60"
                controls-position="right"
                class="number-input"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="最大告警次数" prop="max_alert_count">
          <el-input-number
            v-model="form.max_alert_count"
            :min="1"
            :max="10"
            controls-position="right"
            class="number-input"
          />
          <span class="form-tip">单个告警周期内的最大告警次数，建议设置为3次</span>
        </el-form-item>
      </div>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useKafkaMonitorStore } from '@/stores/kafkaMonitor'
import { ElMessage } from 'element-plus'
import { componentLogger } from '@/utils/logger'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  monitor: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const kafkaMonitorStore = useKafkaMonitorStore()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref()
const loading = ref(false)

const form = ref({
  topic_name: '',
  partition_id: 0,
  status: 'active',
  is_monitored: 1,
  is_alert_enabled: 0,
  alert_threshold_hours: 24,
  webhook_url: '',
  alert_first_send_time: '09:30:00',
  alert_second_interval: 7200,
  alert_third_interval: 21600,
  max_alert_count: 3
})

// 用于时间选择器的独立变量
const formAlertTime = ref(null)

// 计算状态显示文本
const statusText = computed(() => {
  const statusMap = {
    'active': '活跃（监控+告警都开启）',
    'inactive': '非活跃（监控+告警都关闭）',
    'monitored_only': '仅监控（仅监控开启）'
  }
  return statusMap[form.value.status] || form.value.status
})

const rules = {
  alert_threshold_hours: [
    { required: true, message: '请输入告警阈值', trigger: 'blur' },
    { type: 'number', min: 1, max: 168, message: '告警阈值应在1-168小时之间', trigger: 'blur' }
  ],
  alert_second_interval: [
    { required: true, message: '请输入第2次告警间隔', trigger: 'blur' },
    { type: 'number', min: 60, max: 86400, message: '间隔应在60-86400秒之间', trigger: 'blur' }
  ],
  alert_third_interval: [
    { required: true, message: '请输入第3次告警间隔', trigger: 'blur' },
    { type: 'number', min: 60, max: 86400, message: '间隔应在60-86400秒之间', trigger: 'blur' }
  ],
  max_alert_count: [
    { required: true, message: '请输入最大告警次数', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '告警次数应在1-10次之间', trigger: 'blur' }
  ]
}

const handleClose = () => {
  visible.value = false
}

const initForm = () => {
  if (props.monitor) {
    form.value = {
      topic_name: props.monitor.topic_name || '',
      partition_id: props.monitor.partition_id || 0,
      status: props.monitor.status || 'active',
      is_monitored: props.monitor.is_monitored || 0,
      is_alert_enabled: props.monitor.is_alert_enabled || 0,
      alert_threshold_hours: props.monitor.alert_threshold_hours || 24,
      webhook_url: props.monitor.webhook_url || '',
      alert_first_send_time: props.monitor.alert_first_send_time || '09:30:00',
      alert_second_interval: props.monitor.alert_second_interval || 7200,
      alert_third_interval: props.monitor.alert_third_interval || 21600,
      max_alert_count: props.monitor.max_alert_count || 3
    }
    
    // 解析时间字符串为Date对象
    if (form.value.alert_first_send_time) {
      const [hours, minutes] = form.value.alert_first_send_time.split(':')
      const date = new Date()
      date.setHours(parseInt(hours), parseInt(minutes), 0, 0)
      formAlertTime.value = date
    }
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 将时间选择器的值转换为字符串格式
    if (formAlertTime.value) {
      const hours = formAlertTime.value.getHours().toString().padStart(2, '0')
      const minutes = formAlertTime.value.getMinutes().toString().padStart(2, '0')
      form.value.alert_first_send_time = `${hours}:${minutes}:00`
    }
    
    // status字段不需要提交，后端会根据开关状态自动计算
    const updateData = {
      is_monitored: form.value.is_monitored,
      is_alert_enabled: form.value.is_alert_enabled,
      alert_threshold_hours: form.value.alert_threshold_hours,
      webhook_url: form.value.webhook_url,
      alert_first_send_time: form.value.alert_first_send_time,
      alert_second_interval: form.value.alert_second_interval,
      alert_third_interval: form.value.alert_third_interval,
      max_alert_count: form.value.max_alert_count
    }
    
    const result = await kafkaMonitorStore.updateMonitor(props.monitor.id, updateData)
    
    if (result.success) {
      emit('success')
      handleClose()
    }
  } catch (error) {
    componentLogger.error('更新监控配置失败:', error)
    if (error !== 'validation failed') {
      ElMessage.error('更新失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

// 监听对话框显示状态
watch(visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 监听monitor变化
watch(() => props.monitor, () => {
  if (visible.value) {
    initForm()
  }
}, { deep: true })
</script>

<style scoped>
/* 对话框使用统一样式系统 */

.monitor-edit-form {
  max-height: 600px;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.form-section:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #409eff;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.section-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  padding: 8px;
  border-radius: 8px;
}

.form-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

.switch-container {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.switch-description {
  flex: 1;
}

.description-title {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.description-text {
  margin: 0;
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
}

.number-input {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

/* 表单项样式优化 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  color: #303133;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-select) {
  width: 100%;
}

/* 滚动条样式 */
.monitor-edit-form::-webkit-scrollbar {
  width: 6px;
}

.monitor-edit-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.monitor-edit-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.monitor-edit-form::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .monitor-edit-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .switch-container {
    flex-direction: column;
    gap: 8px;
  }
}
</style>

